#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define ID_PATH "data/id.dat"
#define MA_PATH "data/managers.dat"
#define SE_PATH "data/services.dat"

#define M_ID 0
#define D_ID 2
#define E_ID 4

using namespace std;

int Init_Id(void)
{
	if(0 == access(ID_PATH,F_OK)) return 0;

	int fd = open(ID_PATH,O_RDWR|O_CREAT|O_TRUNC,0644);
	if(0 > fd)
	{
		perror("open");
		return -1;
	}

	int id = M_ID;
	int ret = write(fd,&id,4);
	if(0 > ret)
	{
		perror("write_m");
		return -1;
	}
	id = D_ID;
	ret = write(fd,&id,4);
	if(0 > ret)
	{
		perror("write_d");
		return -1;
	}
	id = E_ID;
	ret = write(fd,&id,4);
	if(0 > ret)
	{
		perror("write_e");
		return -1;
	}

	lseek(fd,SEEK_SET,0);
	
	read(fd,&id,4);
	printf("%d\n",id);
	read(fd,&id,4);
	printf("%d\n",id);
	read(fd,&id,4);
	printf("%d\n",id);

	close(fd);

	return 0;
}

int get_Id(int m)
{
	int fd = open(ID_PATH,O_RDWR);
	if(0 > fd)
	{
		perror("open_get");
		return -1;
	}

	int id = 3;
	read(fd,&id,4);
	printf("%d\n",id);
	read(fd,&id,4);
	printf("%d\n",id);
	read(fd,&id,4);
	printf("%d\n",id);

	lseek(fd,SEEK_SET,0);
	//read(fd,&id,4);
	for(int i=0;i<m;i++)
	{
		read(fd,&id,4);
	}
	printf("%d\n",id);
	id++;
	int ret = write(fd,&id,4);
	if(0 > ret)
	{
		perror("write");
		return -1;
	}
	return id;
}

int main()
{
	Init_Id();
	get_Id(2);
}
